package org.jeeasy.common.core.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 请求计时拦截器
 *
 * @author wei.yang
 * @date 2022-09-12 13:53
 */
@Slf4j
@Component
public class RequestTimingInterceptor implements HandlerInterceptor {
    private static final String TIMING_START_KEY = "__START_TIME__";
    private static final String TIMING_HANDLE_KEY = "__HANDLE_TIME__";

    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        long start = System.currentTimeMillis();
        request.setAttribute(TIMING_START_KEY, start);
        return true;
    }

    /**
     * 访问控制器方法后执行
     */
    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, ModelAndView modelAndView) {
        long start = (long) request.getAttribute(TIMING_START_KEY);
        long end = System.currentTimeMillis();
        request.setAttribute(TIMING_HANDLE_KEY, end - start);
    }

    /**
     * postHandle方法执行完成后执行，一般用于释放资源
     */
    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
        Long handleTime = (Long) request.getAttribute(TIMING_HANDLE_KEY);
        if (handleTime != null) {
            log.info("[({}) {}]耗时[{}]毫秒", request.getMethod(), request.getRequestURL(), handleTime);
        } else {
            log.warn("未能获取到请求处理时间");
        }
    }
}
